<template>
  <div class="AddPack">
    <div class="cus-title"><h4>新增打包活动</h4></div>
    <div class="cus-update">
      <el-form ref="form" :model="BindForm" :rules="rules" label-width="120px" label-position="left">
        <el-form-item label="活动名称:" prop="actName">
          <el-col :span="24">
            <el-input v-model="BindForm.actName" maxlength="20" class="cus-input" clearable />
          </el-col>
        </el-form-item>
        <el-form-item label="活动描述:" prop="actDesc">
          <el-col :span="24">
            <el-input v-model="BindForm.actDesc" maxlength="30" class="cus-input" clearable />
          </el-col>
        </el-form-item>
        <el-form-item label="活动时间:" prop="actTimes">
          <el-col :span="24">
            <el-date-picker
              v-model="BindForm.actTimes"
              type="datetimerange"
              range-separator="至"
              start-placeholder="活动开始时间"
              end-placeholder="活动结束时间"
              align="center"
              clearable
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="活动商品:" prop="actGoodsType">
          <el-col :span="24">
            <el-button
              v-if="BindForm.actGoodsType == 0"
              type="text"
              style="margin-right: 30px;"
              @click="$refs.addActGoodsDialog.show()"
            >添加活动商品</el-button>
            <el-radio-group v-model="BindForm.actGoodsType">
              <el-radio :label="0">部分商品</el-radio>
              <el-radio :label="1">全部商品</el-radio>
            </el-radio-group>
          </el-col>
          <el-col v-if="BindForm.actGoodsType == 0 && BindForm.actGoodsList && BindForm.actGoodsList.length > 0" :span="24" style="margin-top: 10px;">
            <el-table
              :data="BindForm.actGoodsList"
              border
              style="width: 100%"
              max-height="400"
            >
              <el-table-column
                label="商品编号"
                prop="goodsId"
                align="center"
                width="130"
                :resizable="false"
                fixed="left"
              />
              <el-table-column label="商品主图" align="center" :resizable="false" width="80">
                <template slot-scope="scope">
                  <TableColumnGoodsImage :src="scope.row.goodsImg" />
                </template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="goodsName"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="商品类型"
                prop="type"
                align="center"
                width="90"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.type == 'lease'" type="success" size="small">租赁</el-tag>
                  <el-tag v-else-if="scope.row.type == 'sale'" type="primary" size="small">售卖</el-tag>
                  <el-tag v-else type="info" size="small">未知</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                header-align="center"
                align="center"
                fixed="right"
                width="100"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-button size="small" type="danger" @click="deleteActGoods(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-form-item>
        <el-form-item label="活动类型:" prop="actType">
          <el-col :span="24">
            <el-radio-group v-model="BindForm.actType">
              <el-radio :label="0">推荐活动</el-radio>
              <el-radio :label="1">组合活动</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="打包商品:" prop="packGoodsList">
          <el-col :span="24">
            <el-button
              type="text"
              @click="$refs.addPackGoodsDialog.show()"
            >添加打包商品</el-button>
          </el-col>
          <el-col v-if="BindForm.packGoodsList && BindForm.packGoodsList.length > 0" :span="24" style="margin-top: 10px;">
            <el-table
              :data="BindForm.packGoodsList"
              border
              style="width: 100%"
              max-height="400"
            >
              <el-table-column
                label="商品编号"
                prop="goodsId"
                align="center"
                width="130"
                :resizable="false"
                fixed="left"
              />
              <el-table-column label="商品主图" align="center" :resizable="false" width="80">
                <template slot-scope="scope">
                  <TableColumnGoodsImage :src="scope.row.goodsImg" />
                </template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="goodsName"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="商品类型"
                prop="type"
                align="center"
                width="90"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.type == 'lease'" type="success" size="small">租赁</el-tag>
                  <el-tag v-else-if="scope.row.type == 'sale'" type="primary" size="small">售卖</el-tag>
                  <el-tag v-else type="info" size="small">未知</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="默认勾选"
                align="center"
                width="130"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-radio-group v-model="BindForm.packGoodsList[scope.$index].checked" size="mini" @change="checkedChange($event, scope.$index)">
                    <el-radio-button :label="0">否</el-radio-button>
                    <el-radio-button :label="1">是</el-radio-button>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column
                label="是否必选"
                align="center"
                width="130"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-radio-group v-model="BindForm.packGoodsList[scope.$index].required" size="mini" @change="requiredChange($event, scope.$index)">
                    <el-radio-button :label="0">否</el-radio-button>
                    <el-radio-button :label="1">是</el-radio-button>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                header-align="center"
                align="center"
                fixed="right"
                width="100"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-button size="small" type="danger" @click="deletePackGoods(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-form-item>
        <el-form-item label="活动门店:" prop="actStoreType">
          <el-col :span="24">
            <el-button
              v-if="BindForm.actStoreType == 0"
              style="margin-right: 30px;"
              type="text"
              @click="$refs.addStoreDialog.show()"
            >添加支持门店</el-button>
            <el-button
              v-else-if="BindForm.actStoreType == 1"
              style="margin-right: 30px;"
              type="text"
              @click="$refs.addStoreDialog.show()"
            >添加不支持门店</el-button>
            <el-radio-group v-model="BindForm.actStoreType">
              <el-radio :label="0">支持部分门店</el-radio>
              <el-radio :label="1">不支持的门店</el-radio>
              <el-radio :label="2">支持全部门店</el-radio>
            </el-radio-group>
          </el-col>
          <el-col v-if="BindForm.actStoreType != 2 && BindForm.storeList && BindForm.storeList.length > 0" :span="24" style="margin-top: 10px;">
            <el-table
              :data="BindForm.storeList"
              border
              style="width: 100%"
              max-height="400"
            >
              <el-table-column
                label="门店编号"
                prop="id"
                align="center"
                width="130"
                :resizable="false"
                fixed="left"
              />
              <el-table-column
                label="门店名称"
                prop="storeName"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="门店地址"
                prop="address"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="操作"
                header-align="center"
                align="center"
                fixed="right"
                width="100"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-button size="small" type="danger" @click="deleteStore(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">确认新增</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <AddGoodsDialog ref="addActGoodsDialog" @select="addActGoods" />
    <AddGoodsDialog ref="addPackGoodsDialog" @select="addPackGoods" />
    <AddStoreDialog ref="addStoreDialog" @select="addStore" />
  </div>
</template>

<script>
import { Loading } from 'element-ui'
import AddGoodsDialog from '../../../components/AddGoodsDialog/index'
import AddStoreDialog from '../../../components/AddStoreDialog/index'
import { addPackAct } from '@/api/market'
import TableColumnGoodsImage from '../../../components/TableColumnGoodsImage/index'
export default {
  name: 'AddPack',
  components: { TableColumnGoodsImage, AddStoreDialog, AddGoodsDialog },
  data() {
    var validateActGoods = (rule, value, callback) => {
      if (this.BindForm.actGoodsType === 0 && this.BindForm.actGoodsList.length <= 0) {
        callback(new Error('请至少添加一个活动商品'))
      } else {
        callback()
      }
    }

    var validatePackGoods = (rule, value, callback) => {
      if (this.BindForm.packGoodsList.length <= 0) {
        callback(new Error('请至少添加一个打包商品'))
      } else {
        callback()
      }
    }

    var validateStore = (rule, value, callback) => {
      if (this.BindForm.actStoreType !== 2 && this.BindForm.storeList.length <= 0) {
        callback(new Error('请至少添加一个门店'))
      } else {
        callback()
      }
    }

    return {
      BindForm: {
        actName: null,
        actDesc: null,
        actTimes: null,
        actGoodsType: 0,
        actType: 0,
        actStoreType: 0,
        actGoodsList: [],
        packGoodsList: [],
        storeList: []
      },
      rules: {
        actName: [{ required: true, message: '请输入活动名称', trigger: 'change' }],
        actDesc: [{ required: true, message: '请输入活动描述', trigger: 'change' }],
        actTimes: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
        actGoodsType: [{ required: true, message: '请选择活动商品', trigger: 'change' }, { validator: validateActGoods, trigger: 'blur' }],
        actType: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
        packGoodsList: [{ required: true, message: '请至少添加一个打包商品', trigger: 'change' }, { validator: validatePackGoods, trigger: 'blur' }],
        actStoreType: [{ required: true, message: '请选择活动门店', trigger: 'change' }, { validator: validateStore, trigger: 'blur' }]
      }
    }
  },
  methods: {
    resetForm() {
      const vm = this
      vm.BindForm.actGoodsList = []
      vm.BindForm.packGoodsList = []
      vm.BindForm.storeList = []
      vm.$refs.form.resetFields()
    },
    submit() {
      const vm = this
      vm.$refs.form.validate((valid) => {
        if (valid) {
          const loadingInstance = Loading.service({ fullscreen: true })
          const data = vm.$XEUtils.clone(vm.BindForm, true)

          if (data.actGoodsType === 0) {
            data.actGoodsList = data.actGoodsList.map(item => {
              return vm.$XEUtils.pick(item, ['goodsId'])
            })
          } else {
            delete data.actGoodsList
          }

          data.packGoodsList = data.packGoodsList.map(item => {
            return vm.$XEUtils.pick(item, ['goodsId', 'checked', 'required'])
          })

          if (data.actStoreType === 0 || data.actStoreType === 1) {
            data.storeList = data.storeList.map(item => {
              return vm.$XEUtils.pick(item, ['id'])
            })
          } else {
            delete data.storeList
          }

          addPackAct(data).then(res => {
            loadingInstance.close()
            vm.$message.success('新增打包活动成功')
            vm.$store.dispatch('tagsView/delView', vm.$route)
            vm.$router.go(-1)
          }).catch(res => {
            loadingInstance.close()
            if (res && res.data && res.data.errno !== 0) {
              this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
            }
          })
        }
      })
    },
    addActGoods(goods) {
      const vm = this

      const res = vm.$XEUtils.find(vm.BindForm.actGoodsList, item => item.goodsId === goods.goodsId)

      if (res) {
        vm.$message.warning('商品已存在，无需重复添加活动商品')
        return
      }

      vm.BindForm.actGoodsList.push(vm.$XEUtils.clone(goods, true))
      vm.$refs.form.validateField('actGoodsType')
    },
    deleteActGoods(index) {
      const vm = this

      vm.BindForm.actGoodsList.splice(index, 1)
      vm.$refs.form.validateField('actGoodsType')
    },
    addPackGoods(goods) {
      const vm = this

      const res = vm.$XEUtils.find(vm.BindForm.packGoodsList, item => item.goodsId === goods.goodsId)

      if (res) {
        vm.$message.warning('商品已存在，无需重复添加打包商品')
        return
      }

      goods.checked = 0
      goods.required = 0
      vm.BindForm.packGoodsList.push(vm.$XEUtils.clone(goods, true))
      vm.$refs.form.validateField('packGoodsList')
    },
    deletePackGoods(index) {
      const vm = this

      vm.BindForm.packGoodsList.splice(index, 1)
      vm.$refs.form.validateField('packGoodsList')
    },
    checkedChange(val, index) {
      const vm = this
      if (val === 0) {
        vm.BindForm.packGoodsList[index].required = 0
      }
    },
    requiredChange(val, index) {
      const vm = this
      if (val === 1) {
        vm.BindForm.packGoodsList[index].checked = 1
      }
    },
    addStore(store) {
      const vm = this

      const res = vm.$XEUtils.find(vm.BindForm.storeList, item => item.id === store.id)

      if (res) {
        vm.$message.warning('门店已存在，无需重复添加门店')
        return
      }

      vm.BindForm.storeList.push(vm.$XEUtils.clone(store, true))
      vm.$refs.form.validateField('actStoreType')
    },
    deleteStore(index) {
      const vm = this

      vm.BindForm.storeList.splice(index, 1)
      vm.$refs.form.validateField('actStoreType')
    }
  }
}
</script>

<style lang="scss" scoped>
  .AddPack {
    padding: 30px;
    .cus-update {
      padding: 20px 30px;
      padding-bottom: 0px;
      margin-bottom: 30px;
      border: 1px solid #eee;

      .cus-input {
        max-width: 400px;
      }
    }
  }
</style>
